# Xray/V2Ray 核心自动下载脚本
# 使用方法: 在 PowerShell 中运行此脚本

Write-Host "================================" -ForegroundColor Cyan
Write-Host "  Xray 核心自动下载工具" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan
Write-Host ""

# 创建核心目录
$coreDir = "xray-core"
if (-not (Test-Path $coreDir)) {
    New-Item -ItemType Directory -Path $coreDir | Out-Null
    Write-Host "✅ 创建目录: $coreDir" -ForegroundColor Green
}

# 获取最新版本
Write-Host "🔍 正在获取 Xray 最新版本..." -ForegroundColor Yellow

try {
    $releasesUrl = "https://api.github.com/repos/XTLS/Xray-core/releases/latest"
    $response = Invoke-RestMethod -Uri $releasesUrl -Method Get
    $version = $response.tag_name
    
    Write-Host "📦 最新版本: $version" -ForegroundColor Green
    
    # 查找 Windows 64位下载链接
    $asset = $response.assets | Where-Object { $_.name -like "*windows-64.zip" }
    
    if ($null -eq $asset) {
        Write-Host "❌ 未找到 Windows 64位版本" -ForegroundColor Red
        exit 1
    }
    
    $downloadUrl = $asset.browser_download_url
    $fileName = $asset.name
    $filePath = Join-Path $coreDir $fileName
    
    Write-Host "📥 开始下载: $fileName" -ForegroundColor Yellow
    Write-Host "   链接: $downloadUrl" -ForegroundColor Gray
    
    # 下载文件（显示进度）
    $ProgressPreference = 'SilentlyContinue'
    Invoke-WebRequest -Uri $downloadUrl -OutFile $filePath
    $ProgressPreference = 'Continue'
    
    Write-Host "✅ 下载完成！" -ForegroundColor Green
    
    # 解压文件
    Write-Host "📦 正在解压..." -ForegroundColor Yellow
    Expand-Archive -Path $filePath -DestinationPath $coreDir -Force
    
    # 删除压缩包
    Remove-Item $filePath
    
    Write-Host "✅ 解压完成！" -ForegroundColor Green
    Write-Host ""
    Write-Host "================================" -ForegroundColor Cyan
    Write-Host "  安装成功！" -ForegroundColor Green
    Write-Host "================================" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "Xray 核心已安装到: $coreDir\xray.exe" -ForegroundColor Green
    Write-Host ""
    Write-Host "下一步:" -ForegroundColor Yellow
    Write-Host "  1. 在应用中添加服务器配置" -ForegroundColor White
    Write-Host "  2. 点击连接按钮" -ForegroundColor White
    Write-Host "  3. 开始访问自由互联网！" -ForegroundColor White
    Write-Host ""
    
} catch {
    Write-Host "❌ 下载失败: $_" -ForegroundColor Red
    Write-Host ""
    Write-Host "请手动下载:" -ForegroundColor Yellow
    Write-Host "  1. 访问: https://github.com/XTLS/Xray-core/releases" -ForegroundColor White
    Write-Host "  2. 下载: Xray-windows-64.zip" -ForegroundColor White
    Write-Host "  3. 解压到: $coreDir\" -ForegroundColor White
    Write-Host ""
}

Read-Host "按 Enter 键退出"
